package com.fll.fangyiuser.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fll.fangyicommon.entity.ResultOk;
import com.fll.fangyicommon.entity.user.Friend;
import com.fll.fangyicommon.entity.user.Message;
import com.fll.fangyicommon.entity.user.User;
import com.fll.fangyiuser.dao.FriendDao;
import com.fll.fangyiuser.dao.OssDao;
import com.fll.fangyiuser.dao.UserDao;
import com.fll.fangyiuser.service.FriendService;
import com.fll.fangyiuser.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author fll
 * @create 2023/2/27
 */
@Slf4j
@Service
public class FriendServiceImpl implements FriendService {

    @Autowired
    private FriendDao friendDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private OssDao ossDao;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 根据两个用户id验证是否为好友
     * @param userId
     * @param friendId
     * @return
     */
    @Override
    public Friend verifyFriend(Integer userId, Integer friendId) {
        Friend friend = friendDao.verifyFriend(userId, friendId);
        if (friend != null){
            if (friend.getState() == 1){
                log.info("userId===>{}和friendId===>{}是好友===>yes", userId,friendId);
                return friend;
            }
            if (friend.getState() == 0){
                log.warn("userId===>{}和friendId===>{}不是好友===>no，但已发送过请求！",userId, friendId);
                return friend;
            }
        }
        log.warn("userId===>{},friendId===>{}不是好友===>no", userId,friendId);
        return null;
    }

    /**
     * 添加好友插入两条记录（而且要么同时成功要么同时失败）
     * @param friend
     * @return
     */
    @Override
    public Integer insert(Friend friend) {
        if (friend == null){
            return null;
        }
        Integer num = friendDao.insert(friend);
        if (num != 0) {
            log.info("发送请求成功,个数===>{}", num);
            return num;
        }
        log.error("发送请求失败,个数===>{}", num);
        return null;
    }

    /**
     * 根据用户id查询Friend
     * state: 0 待同意
     * state：1 已同意
     * @param userId
     * @param state
     * @return
     */
    public List<Friend> getFriendByUserId(Integer userId,Integer state){
        List<Friend> friendList = friendDao.getFriendByUserId(userId, state);
        if (friendList.size() != 0){
            log.info("查询用户：{}好友成功===>{},好友数===>{}",userId, friendList, friendList.size());
            return friendList;
        }
        log.warn("查询用户：{}好友为空,暂无好友", userId);
        return null;
    }

    /**
     * 同意好友申请
     * @param friendId
     * @return
     */
    @Override
    public Integer agreeFriend(Integer friendId, Integer userId) {
        Integer num = friendDao.agreeFriend(friendId, userId);
        if (num != 0) {
            log.info("同意成功,个数===>{}", num);
            return num;
        }
        log.warn("同意失败,个数===>{}", num);
        return 0;
    }

    /**
     * 删除好友
     * @param friendId
     * @param userId
     * @return
     */
    @Override
    public Integer deleteFriend(Integer userId, Integer friendId) {
        Integer num = friendDao.deleteFriend(userId, friendId);
        if (num != 0) {
            log.info("删除成功,个数===>{}", num);
            return num;
        }
        log.warn("删除失败,个数===>{}", num);
        return 0;
    }

    /**
     * 获取用户添加的好友数
     * @param userId
     * @return
     */
    @Override
    public Integer getFriendCount(Integer userId){
        return friendDao.getFriendCount(userId);
    }

    /**
     * 查询登录用户所有好友id
     * @param userId
     * @return
     */
    @Override
    public String getFriendByRpc(Integer userId){
        List<Integer> userIds = friendDao.getFriendByRpc(userId);
        if(userIds != null || userIds.size() != 0){
            StringBuilder sb = new StringBuilder("(");
            for(Integer id : userIds){
                sb.append(id);
                sb.append(",");
            }
            sb.deleteCharAt(sb.length() - 1);
            sb.append(")");
            return sb.toString();
        }
        return null;
    }

    /**
     * 获取相同好友
     * 思路：把好友的friend和当前登录用户的friend查询出来，通过set集合对id去重
     * @param userId 当前登录用户id
     * @param friendId 好友的id
     * @return
     */
    @Override
    public ResultOk getSameFriend(Integer userId, Integer friendId){
        ResultOk<List<User>> ok = new ResultOk<>();
        Set<Integer> friendSetA = new HashSet<>();
        Set<Integer> friendSetB = new HashSet<>();
        Set<Integer> resSet = new HashSet<>();

        // state：1已同意的好友
        List<Integer> friendByUser = friendDao.getFriend(userId, 1);
        if (friendByUser != null){
            for (Integer u1 : friendByUser){
                friendSetA.add(u1);
            }
        }
        log.info("当前登录用户===>{}, 好友===>{}",userId,friendSetA);
        List<Integer> friendByFriend = friendDao.getFriend(friendId, 1);
        if (friendByFriend != null){
            for (Integer u2 : friendByFriend){
                friendSetB.add(u2);
            }
        }
        log.info("好友id===>{}, 好友的好友===>{}",friendId,friendSetB);
        resSet.addAll(friendSetA);
        resSet.retainAll(friendSetB);

        Iterator<Integer> it = resSet.iterator();
        List<User> users = new ArrayList<>();
        while (it.hasNext()){
            Integer id = it.next();
            User user = userDao.getUserInfoByUserId(id);
            user.setOss(ossDao.selectOssByUserId(id));
            users.add(user);
        }
        log.info("共同的好友===>{}",resSet);
        ok.setCode(200);
        ok.setMsg("获取共同好友成功");
        ok.setData(users);
        return ok;
    }

}
